var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var weixin = require('weixin-api');
var data = require('./msgHandleData');

// config
weixin.token = 'jambuspublicwechat';

//var wechatConnectTest = false;

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

//接入测试
/*
app.use('/wechat', function (req, res, next) {
  console.log(req.body);
  if(wechatConnectTest){
    var echostr = req.query.echostr;
    console.log("Connect test(request echostr):"+ echostr);
    res.send(echostr);
  }
});
*/

// 接入验证
app.get('/wechat', function(req, res) {

    // 签名成功
    if (weixin.checkSignature(req)) {
        res.send(200, req.query.echostr);
    } else {
        res.send(200, 'fail');
    }
});

// 监听文本消息
weixin.textMsg(function(msg) {
    console.log("textMsg received");
    console.log(JSON.stringify(msg));

    data.handler(msg.content,function(reply){

    var resMsg = {};

    if(reply.msgType === "text"){
    resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : reply.msgType,
                content : reply.answer,
                funcFlag : 0
            };
    }else{
      resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : reply.msgType,
                content : reply.answer,
                funcFlag : 0
            };

    }
    
    /*
    switch (msg.content) {
        case "文本" :
            // 返回文本消息
            resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : "text",
                content : "这是文本回复",
                funcFlag : 0
            };
            break;

        case "音乐" :
            // 返回音乐消息
            resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : "music",
                title : "音乐标题",
                description : "音乐描述",
                musicUrl : "音乐url",
                HQMusicUrl : "高质量音乐url",
                funcFlag : 0
            };
            break;

        case "图文" :

            var articles = [];
            articles[0] = {
                title : "PHP依赖管理工具Composer入门",
                description : "PHP依赖管理工具Composer入门",
                picUrl : "http://weizhifeng.net/images/tech/composer.png",
                url : "http://weizhifeng.net/manage-php-dependency-with-composer.html"
            };

            articles[1] = {
                title : "八月西湖",
                description : "八月西湖",
                picUrl : "http://weizhifeng.net/images/poem/bayuexihu.jpg",
                url : "http://weizhifeng.net/bayuexihu.html"
            };

            articles[2] = {
                title : "「翻译」Redis协议",
                description : "「翻译」Redis协议",
                picUrl : "http://weizhifeng.net/images/tech/redis.png",
                url : "http://weizhifeng.net/redis-protocol.html"
            };

            // 返回图文消息
            resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : "news",
                articles : articles,
                funcFlag : 0
            }
    }
    */

    weixin.sendMsg(resMsg);
    });
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

// 监听事件消息
weixin.eventMsg(function(msg) {
    console.log("eventMsg received");
    console.log(JSON.stringify(msg));
    
    if((msg.msgType === "event") && (msg.event === "subscribe")) {
        var articles = [];
            articles[0] = {
                title : "[欢迎关注果酱公众号]",
                description : "额，国庆大家都出去high了，在家无聊写个脑残聊天机器人玩...自己回复自己玩...呵呵...",
                picUrl : "http://image.tianjimedia.com/uploadImages/2014/119/43/1RRJ4172545A_1000x500.jpg",
                url : "http://blog.sina.com.cn/jambus"
            };

        var resMsg = {
                fromUserName : msg.toUserName,
                toUserName : msg.fromUserName,
                msgType : "news",
                articles : articles,
                funcFlag : 0
            };
        weixin.sendMsg(resMsg);
    }
});

// Start
app.post('/wechat', function(req, res) {
    // loop
    weixin.loop(req, res);

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.listen(80, function(){
  console.log("Express server listening");
});

module.exports = app;